﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace editor.cfg
{
  

    public class Manager
    {
        public static readonly Manager Ins = new Manager();

        public Defines Defines { get { return Configs.Defines; } }
        public Configs Configs { get; private set; }


        private string _cfgXmlPath;
        public string CfgXmlPath
        {
            get
            {
                return _cfgXmlPath;
            }
            set
            {
                _cfgXmlPath = value;
                Properties.Settings.Default.cfgxmlpath = value;
                Properties.Settings.Default.Save();
            }
        }

        public Manager()
        {
            this._cfgXmlPath = Properties.Settings.Default.cfgxmlpath;
        }

        public bool ChooseCfgXmlFile()
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "配置根文件(cfg.xml)|*.xml";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = false;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                CfgXmlPath = openFileDialog1.FileName;
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool Load()
        {

            var configs = new Configs();

            if(!File.Exists(CfgXmlPath) && MessageBox.Show("无法打开配置根文件(cfg.xml)，是否重新选择？", "打开失败", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (!ChooseCfgXmlFile())
                {
                    MessageBox.Show("未正确设置配置根定义文件(cfg.xml)的位置,加载失败。请使用菜单 文件 -> 重新加载配置  进行设置");
                    return false;
                }
            }


            if (configs.Load(CfgXmlPath))
            {
                Configs = configs;
                return true;
            }
            else
            {
                MessageBox.Show($"{CfgXmlPath} 加载失败, 请先check配置正确");
                return false;
            }
        }
    }
}
